package com.xdcplus.web.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xdcplus.exceptions.XdcWebException;
import com.xdcplus.mom.enums.ResponseEnum;
import com.xdcplus.web.common.enums.DmSortingSummaryEnum;
import com.xdcplus.web.common.pojo.dto.DmSortingSummaryDTO;
import com.xdcplus.web.common.pojo.dto.DwWorkDateDTO;
import com.xdcplus.web.common.pojo.entity.DmSortingSummary;
import com.xdcplus.web.common.pojo.entity.DwWorkConf;
import com.xdcplus.web.common.pojo.vo.*;
import com.xdcplus.web.mapper.DmSortingMapper;
import com.xdcplus.web.service.CommonService;
import com.xdcplus.web.service.DmSortingService;
import com.xdcplus.web.service.DwWorkDateService;
import com.xdcplus.web.common.utils.DmSummaryUtil;
import com.xdcplus.web.common.pojo.vo.PmShiftManageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 利珀  - 检测设备 服务实现类
 * </p>
 *
 * @author xukw
 * @since 2023-11-06
 */
@Service
@Slf4j
public class DmSortingServiceImpl extends ServiceImpl<DmSortingMapper, DmSortingSummary> implements DmSortingService {

    @Autowired
    protected DmSortingMapper dmSortingMapper;

    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private CommonService commonService;
    @Autowired
    private DwWorkDateService workDateService;

    @Override
    public void execute(DwWorkConf dwWorkConf) {

        LocalDateTime endDateTime = dwWorkConf.getEtlEndTimestamp().toLocalDateTime().withSecond(0);
        LocalDateTime startDateTime = dwWorkConf.getEtlStartTimestamp().toLocalDateTime().withSecond(0);

        PmShiftManageVO pmShiftByDate = commonService.getPmShiftByDate(Date.from(startDateTime.atZone(ZoneId.systemDefault()).toInstant()));


        String startDateTimeStr = startDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String endDateTimeStr = endDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        log.info("正背膜分选机5分钟清洗一次，清洗时间：{}-{}", startDateTimeStr, endDateTimeStr);

        List<DmSortingSummary> summaryList = dmSortingMapper.executeQueryDate(startDateTimeStr, endDateTimeStr);
        String summaryDate = endDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String dateId = endDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        summaryList.forEach(
                dmSortingSummary -> {
                    dmSortingSummary.setSummaryDate(summaryDate);
                    dmSortingSummary.setDateId(dateId);
                    dmSortingSummary.setShiftDate(pmShiftByDate.getShiftDate());
                    dmSortingSummary.setShiftName(pmShiftByDate.getShiftName());
                    dmSortingSummary.setShiftCode(pmShiftByDate.getShiftCode());
                }
        );
        transactionTemplate.executeWithoutResult(
                transactionStatus -> {
                    saveBatch(summaryList);
                }
        );
        log.info("正背膜分选机清洗完成，清洗时间：{}-{}", startDateTimeStr, endDateTimeStr);
    }

    @Override
    public void compensateBuildData(DwWorkConf dwWorkConf) {

        LocalDateTime localDateTime = dwWorkConf.getEndTimestamp().toLocalDateTime();
        LocalDateTime summaryDateTime = dwWorkConf.getStartTimestamp().toLocalDateTime();

        List<String> summaryDates = dmSortingMapper.findSummaryDate(summaryDateTime.format(
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        while (summaryDateTime.isBefore(localDateTime)) {

            String dateStr = summaryDateTime.format(
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:00"));

            dwWorkConf.setEtlStartTimestamp(
                    Timestamp.from(summaryDateTime
                            .minusMinutes(dwWorkConf.getEtlQueryMinute())
                            .atZone(ZoneId.systemDefault()).toInstant())
            );
            dwWorkConf.setEtlEndTimestamp(
                Timestamp.from(summaryDateTime.atZone(ZoneId.systemDefault()).toInstant())
            );

            if (!summaryDates.contains(dateStr)) {
                log.error("dmSortingHandler补充: --- {}", dateStr);
                execute(dwWorkConf);
            }
            summaryDateTime = summaryDateTime.plusMinutes(5);

        }

    }

    @Override
    public List<DmSortingSummaryTypeVO> querySortingInfo(DmSortingSummaryDTO dmSortingSummaryDTO) {
        List<DmSortingSummaryTypeVO> newList = new ArrayList<>();
        List<DmSortingSummaryTypeVO> listSum = dmSortingMapper.querySortingSummaryInfo(dmSortingSummaryDTO);
        List<DmSortingSummaryTypeVO> BMSummary = findDmSortingSummaryByType("BM", listSum);
        List<DmSortingSummaryTypeVO> ZMSummary = findDmSortingSummaryByType("ZM", listSum);
        newList.addAll(BMSummary);
        newList.addAll(ZMSummary);
        log.info("正背膜分选机查询结果:{}", newList);

        return newList;
    }

    @Override
    public DmReworkSummaryAllVO queryReworkInfo(DmSortingSummaryDTO dmSortingSummaryDTO) {
        if (StrUtil.isEmpty(dmSortingSummaryDTO.getStartTime()) || StrUtil.isEmpty(dmSortingSummaryDTO.getEndTime())) {
            throw new XdcWebException(ResponseEnum.ERROR, "时间不能为空");
        }
        DmReworkSummaryAllVO dmReworkSummaryAllVO = new DmReworkSummaryAllVO();
        List<DmReworkSummaryVO> listSum = dmSortingMapper.queryReworkSummaryInfo(dmSortingSummaryDTO);
        listSum.stream().forEach(dmReworkSummaryVO -> {
            //获取班别
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                PmShiftManageVO pmShiftManageVO = commonService.getPmShiftByDate(sdf.parse(dmReworkSummaryVO.getSummaryDate()));
                dmReworkSummaryVO.setTeam(pmShiftManageVO.getShiftName());
            } catch (ParseException e) {
                log.error("获取班别失败！");
                e.printStackTrace();
            }
        });
        //班别汇总
        if (dmSortingSummaryDTO.getTeam() != null) {
            listSum = listSum.stream().filter(s -> dmSortingSummaryDTO.getTeam().equals(s.getTeam())).collect(Collectors.toList());
        }
        dmReworkSummaryAllVO.setQualitySum(listSum);
        //日期汇总
        List<String> dateList = DmSummaryUtil.rangeToList(dmSortingSummaryDTO.getStartTime(), dmSortingSummaryDTO.getEndTime());
        List<DmReworkSummaryVO> listDmReworkSummaryVOByDate = dmSortingMapper.findReworkSummaryByWeekMonth(dmSortingSummaryDTO);
        List<DmReworkSummaryDateVO> listSumDate = new ArrayList<>();
        for (String str : dateList) {
            DmReworkSummaryDateVO dmReworkSummaryDateVO = new DmReworkSummaryDateVO();
            List<DmReworkSummaryVO> dateListSum = listDmReworkSummaryVOByDate.stream().filter(s -> str.equals(s.getDateId())).collect(Collectors.toList());
            dmReworkSummaryDateVO.setFabDate(str);
            List<DmReworkSummaryQualityVO> quality = quailtyDetail("ZM", dateListSum);
            quality.addAll(quailtyDetail("BM", dateListSum));
            dmReworkSummaryDateVO.setQuality(quality);
            listSumDate.add(dmReworkSummaryDateVO);
        }
        //周月汇总
        if (dmSortingSummaryDTO.getMonthDimension() || dmSortingSummaryDTO.getWeekDimension()) {
            if (StrUtil.isEmpty(dmSortingSummaryDTO.getStartMonth()) || StrUtil.isEmpty(dmSortingSummaryDTO.getEndMonth())) {
                throw new XdcWebException(ResponseEnum.ERROR, "月份不能为空");
            }
            DwWorkDateDTO dateDTO = new DwWorkDateDTO();
            dateDTO.setStartMonth(dmSortingSummaryDTO.getStartMonth().replace("-", ""));
            dateDTO.setEndMonth(dmSortingSummaryDTO.getEndMonth().replace("-", ""));
            List<DwWorkDateVO> dates = workDateService.findWeekByMonth(dateDTO);
            if (CollUtil.isNotEmpty(dates)) {
                List<String> listWeek = dates.stream().map(DwWorkDateVO::getFabCode).filter(Objects::nonNull).distinct().collect(Collectors.toList());
                List<String> listMonth = dates.stream().map(DwWorkDateVO::getFabDesc).filter(Objects::nonNull).distinct().collect(Collectors.toList());
                dmSortingSummaryDTO.setMonthList(listMonth);
                dmSortingSummaryDTO.setWeekList(listWeek);
                List<DmReworkSummaryVO> listDmReworkSummaryVOByYW = dmSortingMapper.findReworkSummaryByWeekMonth(dmSortingSummaryDTO);
                if (dmSortingSummaryDTO.getWeekDimension()) {
                    for (String str : listWeek) {
                        DmReworkSummaryDateVO dmReworkSummaryDateVO = new DmReworkSummaryDateVO();
                        List<DmReworkSummaryVO> dateListSum = listDmReworkSummaryVOByYW.stream().filter(s -> str.equals(s.getWeekId())).collect(Collectors.toList());
                        dmReworkSummaryDateVO.setFabDate(str.substring(4) + "周");
                        List<DmReworkSummaryQualityVO> quality = quailtyDetail("ZM", dateListSum);
                        quality.addAll(quailtyDetail("BM", dateListSum));
                        dmReworkSummaryDateVO.setQuality(quality);
                        listSumDate.add(dmReworkSummaryDateVO);

                    }
                }
                if (dmSortingSummaryDTO.getMonthDimension()) {
                    for (String str : listMonth) {
                        DmReworkSummaryDateVO dmReworkSummaryDateVO = new DmReworkSummaryDateVO();
                        List<DmReworkSummaryVO> dateListSum = listDmReworkSummaryVOByYW.stream().filter(s -> str.equals(s.getMonthId())).collect(Collectors.toList());
                        dmReworkSummaryDateVO.setFabDate(str.substring(4) + "月");
                        List<DmReworkSummaryQualityVO> quality = quailtyDetail("ZM", dateListSum);
                        quality.addAll(quailtyDetail("BM", dateListSum));
                        dmReworkSummaryDateVO.setQuality(quality);
                        listSumDate.add(dmReworkSummaryDateVO);
                    }
                }
            }

        }
        dmReworkSummaryAllVO.setQualityDate(listSumDate);


        List<DmReworkChartVO> dmReworkChartVOS = dmSortingMapper.queryHistogramData(dmSortingSummaryDTO);
        Map<String, Object> histogramMap = new HashMap<>();

        dmReworkChartVOS.stream()
            .collect(
            Collectors.groupingBy(dmReworkChartVO -> dmReworkChartVO.getItemType())
        ).forEach((itemType,dmReworkChartVOSByType)->{

            List<Long> bayCodes = dmReworkChartVOSByType.stream().map(
                            DmReworkChartVO::getBayCode
                    ).map(Long::parseLong).sorted().distinct()
                    .collect(Collectors.toList());

            Map<String, Object> histogramItemMap = new HashMap<>();

            histogramItemMap.put("xAxis",bayCodes);

            List<ChartVO> histogramSeries = new ArrayList<>();
            dmReworkChartVOSByType.stream()
                    .filter(V -> !"0".equals(V.getNgName()) && !StrUtil.isEmpty(V.getNgName()))
            .collect(Collectors.groupingBy(
                DmReworkChartVO::getNgName
            )).forEach((ngName,itemList)->{
                ChartVO chartVO1 = new ChartVO();
                chartVO1.setName(ngName);
                for (Long bayCode : bayCodes) {
                    chartVO1.getData()
                    .add(
                        itemList.stream()
                        .filter(V->V.getBayCode().equals(String.valueOf(bayCode)))
                        .collect(Collectors.summingLong(DmReworkChartVO::getNgNumber))
                    );
                }
                histogramSeries.add(chartVO1);
            });
            histogramItemMap.put("series",histogramSeries);
            histogramMap.put(itemType,histogramItemMap);

            List<Double> histogramOkSeries = new ArrayList<>();
            for (Long bayCode : bayCodes) {

                Long totalByBayCode = dmReworkChartVOSByType
                        .stream()
                        .filter(V -> V.getBayCode().equals(String.valueOf(bayCode)) && !StrUtil.isEmpty(V.getNgName()))
                        .collect(Collectors.summingLong(DmReworkChartVO::getNgNumber));

                Long okTotal = dmReworkChartVOSByType
                        .stream()
                        .filter(V -> "0".equals(V.getNgName()) && V.getBayCode().equals(String.valueOf(bayCode)) && !StrUtil.isEmpty(V.getNgName()))
                        .collect(Collectors.summingLong(DmReworkChartVO::getNgNumber));

                histogramOkSeries.add(calculatePercent(okTotal,totalByBayCode));

            }

            histogramItemMap.put("series2",histogramOkSeries);
            histogramMap.put(itemType,histogramItemMap);


        });

        dmReworkSummaryAllVO.setHistogramSummary(histogramMap);



        /// 柏拉图
        List<DmReworkChartVO> dmPlatoReworkChartVOS = dmSortingMapper.queryPlatoSummaryData(dmSortingSummaryDTO);
        Map<String, Object> platoMap = new HashMap<>();
        Map<String, Object> pieMap = new HashMap<>();
        dmPlatoReworkChartVOS.stream()
            .collect(
            Collectors.groupingBy(DmReworkChartVO::getItemType)
        ).forEach((itemType,dmPlatoReworkChartVOSByType)->{

            Long platoTotal = dmPlatoReworkChartVOSByType.stream().collect(Collectors.summingLong(DmReworkChartVO::getNgNumber));
            Long platoPoorTotal = dmPlatoReworkChartVOSByType.stream().filter(V-> !"0".equals(V.getNgName())).collect(Collectors.summingLong(DmReworkChartVO::getNgNumber));
            List<String> platoXAxis = new ArrayList<>();
            List<Long> platoNumSeries = new ArrayList<>();
            List<String> platoPoorRateSeries = new ArrayList<>();
            List<String> platoAllRateSeries = new ArrayList<>();
            dmPlatoReworkChartVOSByType.stream()
            .filter(V-> !"0".equals(V.getNgName())).sorted(
                Comparator.comparing(DmReworkChartVO::getNgNumber).reversed()
            ).forEach(dmReworkChartVO -> {
                platoXAxis.add(dmReworkChartVO.getNgName());
                platoNumSeries.add(dmReworkChartVO.getNgNumber());
                /// 不拉图，不良占比取反
                if (platoPoorTotal>0) {
                    platoPoorRateSeries.add(
                            String.format("%.2f",100-dmReworkChartVO.getNgNumber()*100d/platoPoorTotal)
                    );
                }
                if (platoTotal>0) {
                    platoAllRateSeries.add(
                            String.format("%.2f",dmReworkChartVO.getNgNumber()*100d/platoTotal)
                    );
                }
            });
            Map<String, Object> platoItemMap = new HashMap<>();
            platoItemMap.put("xAxis",platoXAxis);
            platoItemMap.put("series1",platoNumSeries);
            platoItemMap.put("series2",platoAllRateSeries);
            platoItemMap.put("series3",platoPoorRateSeries);

            platoMap.put(itemType,platoItemMap);

            List<DmReworkReverseVO> itemPieSeries = dmPlatoReworkChartVOSByType.stream().map(
                    dmReworkChartVO -> {
                        DmReworkReverseVO dmReworkReverseVO = new DmReworkReverseVO();
                        dmReworkReverseVO.setName(dmReworkChartVO.getNgName());
                        dmReworkReverseVO.setValue(dmReworkChartVO.getNgNumber() * 1d / platoPoorTotal);
                        dmReworkReverseVO.setPoorRate(dmReworkChartVO.getNgNumber() * 1d / platoPoorTotal);
                        dmReworkReverseVO.setTotalRate(dmReworkChartVO.getNgNumber() * 1d / platoTotal);
                        dmReworkReverseVO.setNgNumber(dmReworkReverseVO.getNgNumber());
                        return dmReworkReverseVO;
                    }
            ).collect(Collectors.toList());
            pieMap.put(itemType,itemPieSeries);

        });
        dmReworkSummaryAllVO.setPlatoPoorSummary(platoMap);
        dmReworkSummaryAllVO.setPieSummary(pieMap);
        return dmReworkSummaryAllVO;
    }

    private Double calculatePercent(Long okTotal, Long totalByBayCode) {
        if (ObjectUtil.isNotEmpty(totalByBayCode)) {
            if (totalByBayCode>0) {
                return BigDecimal.valueOf(okTotal)
                        .divide(BigDecimal.valueOf(totalByBayCode),
                                4,BigDecimal.ROUND_HALF_UP)
                        .multiply(BigDecimal.valueOf(100))
                        .doubleValue();
            }
        }
        return 0d;

    }

    @Override
    public Map<String,Object> querySortingSearchInfo() {
        List<DmReworkChartVO> dmReworkChartVOS =  baseMapper.querySortingSearchInfo();
        Map<String, Object> searchInfoMap = new HashMap<>();
        dmReworkChartVOS.stream().collect(
                Collectors.groupingBy(DmReworkChartVO::getItemType)
        ).forEach((itemType,dmReworkChartVOSByType)->{
            Map<String, Object> searchInfoItemMap = new HashMap<>();
            searchInfoItemMap.put("bayCodes",dmReworkChartVOSByType.stream().map(
                    DmReworkChartVO::getBayCode
            ).filter(ObjectUtil::isNotEmpty)
                            .map(Integer::parseInt).distinct()
                    .sorted(Comparator.comparing(Function.identity())).collect(Collectors.toList()));
            searchInfoItemMap.put("tureCodes",dmReworkChartVOSByType.stream().map(
                    DmReworkChartVO::getTubeCode
            ).filter(ObjectUtil::isNotEmpty).distinct()
                    .map(Integer::parseInt).sorted(Comparator.comparing(Function.identity())).collect(Collectors.toList()));
            searchInfoItemMap.put("boatCodes",dmReworkChartVOSByType.stream().map(
                    DmReworkChartVO::getBoatCode
            ).filter(ObjectUtil::isNotEmpty).distinct()
                    .sorted(Comparator.comparing(Function.identity())).collect(Collectors.toList()));
            searchInfoMap.put(itemType,searchInfoItemMap);
        });
        return searchInfoMap;
    }

    @Override
    public Map<String, Object> queryReworkInfoHotChart(DmSortingSummaryDTO dmSortingSummaryDTO) {
        List<DmReworkChartVO> dmReworkChartVOS = baseMapper.queryHotSummaryData(dmSortingSummaryDTO);

        Map<String, Object> hotHashMap = new HashMap<>();

        List<DmReworkChartVO> reworkChartVOList1 = dmReworkChartVOS.stream()
                .filter(
                        V -> ObjectUtil.isNotEmpty(V.getTubeCode())
                ).collect(Collectors.toList());

        List<String> classNames = Arrays.asList("ZM", "BM");

        reworkChartVOList1.stream().collect(
                Collectors.groupingBy(DmReworkChartVO::getItemType)
        ).forEach((className,dmReworkChartVOList)->{
            ///
            if (classNames.contains(className)) {
                Map<String, Object> itemMap = new HashMap<>();
                /// 舟号序列
                List<String> xAxis = dmReworkChartVOList.stream()
                    .sorted(Comparator.comparing(
                        DmReworkChartVO::getTubeCode
                    )).map(
                            DmReworkChartVO::getTubeCode
                    ).distinct().collect(Collectors.toList());

                /// 管号
                List<String> boats = dmReworkChartVOList.stream().map(
                        DmReworkChartVO::getBoatCode
                ).distinct().collect(Collectors.toList());

                List<ChartVO> series = new ArrayList<>();

                boats.forEach(boat->{
                    ChartVO chartExtendVO = new ChartVO();
                    chartExtendVO.setName(boat);
                    List<Long> numList = new ArrayList<>();
                    xAxis.forEach(x->{
                        numList.add(
                        dmReworkChartVOList.stream()
                                .filter(
                                    dmReworkChartVO ->
                                            boat.equals(dmReworkChartVO.getBoatCode())
                                        && x.equals(dmReworkChartVO.getTubeCode())
                                ).collect(Collectors.summingLong(DmReworkChartVO::getNgNumber)));
                    });
                    chartExtendVO.setData(numList);
                    series.add(chartExtendVO);
                });
                itemMap.put("xAxis",xAxis);
                itemMap.put("series",series);
                hotHashMap.put(className,itemMap);
            }
        });

        return hotHashMap;

    }

    private List<DmReworkSummaryQualityVO> quailtyDetail(String itemType, List<DmReworkSummaryVO> listSum) {
        List<DmReworkSummaryQualityVO> listQualityVO = new ArrayList<>();
        //总数
        Long lineSum = listSum.stream().filter(s -> itemType.equals(s.getItemType())).collect(Collectors.summingLong(DmReworkSummaryVO::getNgNumber));
        //OK总数
        Long lineOK = listSum.stream().filter(s -> "0".equals(s.getNgName()) && itemType.equals(s.getItemType())).collect(Collectors.summingLong(DmReworkSummaryVO::getNgNumber));
        String okRatio = String.format("%.2f", lineSum.equals(0L) ? 0.00f : (float) lineOK / (float) lineSum * 100) + "%";
        DmReworkSummaryQualityVO okQualityVO = DmReworkSummaryQualityVO.builder().item("OK").itemQuantity(String.valueOf(lineOK)).itemType(itemType).itemRatio(okRatio).build();
        listQualityVO.add(okQualityVO);
        for (int i = 3; i < DmSortingSummaryEnum.values().length; i++) {
            DmReworkSummaryQualityVO qualityVO = new DmReworkSummaryQualityVO();
            String code = DmSortingSummaryEnum.values()[i].getCode();
            //不良项总数
            Long lineBad = listSum.stream().filter(s -> code.equals(s.getNgName()) && itemType.equals(s.getItemType())).collect(Collectors.summingLong(DmReworkSummaryVO::getNgNumber));
            String ratio = String.format("%.2f", lineSum.equals(0L) ? 0.00f : (float) lineBad / (float) lineSum * 100) + "%";

            qualityVO.setItem(code);
            qualityVO.setItemQuantity(String.valueOf(lineBad));
            qualityVO.setItemRatio(ratio);
            qualityVO.setItemType(itemType);
            listQualityVO.add(qualityVO);
        }
        return listQualityVO;
    }

    private List<DmSortingSummaryTypeVO> findDmSortingSummaryByType(String itemType, List<DmSortingSummaryTypeVO> listSum) {
        List<DmSortingSummaryTypeVO> newList = new ArrayList<>();
        //总数
        Long lineSum = listSum.stream().filter(s -> itemType.equals(s.getItemType())).collect(Collectors.summingLong(DmSortingSummaryTypeVO::getNgNumber));
        //OK总数
        Long lineOkSum = listSum.stream().filter(s -> "0".equals(s.getNgName()) && itemType.equals(s.getItemType())).collect(Collectors.summingLong(DmSortingSummaryTypeVO::getNgNumber));
        DmSortingSummaryTypeVO OkSum = DmSortingSummaryTypeVO.builder().ngName("OK").ngNumber(lineOkSum).rowNo("1").itemType(itemType).build();
        //不OK总数
        Long lineNoOkSum = listSum.stream().filter(s -> !"0".equals(s.getNgName()) && itemType.equals(s.getItemType())).collect(Collectors.summingLong(DmSortingSummaryTypeVO::getNgNumber));
        DmSortingSummaryTypeVO NoOkSum = DmSortingSummaryTypeVO.builder().ngName("不OK").ngNumber(lineNoOkSum).rowNo("2").itemType(itemType).build();
        //色差不OK总数
        Long lineCaNoOkSum = listSum.stream().filter(s -> (DmSortingSummaryEnum.局部跳色.getCode().equals(s.getNgName()) || DmSortingSummaryEnum.边缘绕镀.getCode().equals(s.getNgName()) || DmSortingSummaryEnum.发红色差.getCode().equals(s.getNgName()) || DmSortingSummaryEnum.发白色差.getCode().equals(s.getNgName()) || DmSortingSummaryEnum.中间跳色.getCode().equals(s.getNgName())) && itemType.equals(s.getItemType())).collect(Collectors.summingLong(DmSortingSummaryTypeVO::getNgNumber));
        DmSortingSummaryTypeVO caNoOkSum = DmSortingSummaryTypeVO.builder().ngName("色差不OK").ngNumber(lineCaNoOkSum).rowNo("3").itemType(itemType).build();

        listSum.add(OkSum);
        listSum.add(NoOkSum);
        listSum.add(caNoOkSum);
        for (DmSortingSummaryEnum e : DmSortingSummaryEnum.values()) {
            DmSortingSummaryTypeVO item = listSum.stream().filter(s -> e.getCode().equals(s.getNgName()) && itemType.equals(s.getItemType())).findAny().orElse(null);
            DmSortingSummaryTypeVO dmSortingSummaryTypeVO = DmSortingSummaryTypeVO.builder().rowNo(e.getRowNo()).ngName(e.getCode()).ngNumber(0L).ngRatio("0.00%").itemType(itemType).build();
            if (item != null) {
                dmSortingSummaryTypeVO.setNgNumber(item.getNgNumber());
                String ratio = String.format("%.2f", lineSum.equals(0L) ? 0.00f : (float) item.getNgNumber() / (float) lineSum * 100) + "%";
                dmSortingSummaryTypeVO.setNgRatio(ratio);
            }
            newList.add(dmSortingSummaryTypeVO);
        }
        return newList;
    }
}
